package cn.itsource.dept.service.impl;

import cn.itsource.dept.domain.Department;
import cn.itsource.dept.mapper.DepartmentMapper;
import cn.itsource.dept.service.IDepartmentService;
import cn.itsource.base.service.impl.IBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xlh
 * @since 2023-01-16
 */
@Service
public class DepartmentServiceImpl extends IBaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    DepartmentMapper departmentMapper;
    @Override
    public List<Department> deptTree() {
        //第一步查询全部
        List<Department> departments = departmentMapper.findAll();

        //儿子找父亲
        for (Department department : departments){
            if(department.getParent_id() != null){//找顶级
                for (Department parent : departments){
                    if (department.getParent_id() == parent.getId()){
                        List<Department> children = parent.getChildren();
                        children.add(department);
                        break;
                    }
                }
            }
        }
        //找顶级
        List<Department> firstTree = departments.stream()
                .filter(department -> department.getParent_id() == null)//过滤出来父id为null
                .collect(Collectors.toList());//转为list
        return firstTree;
    }
}
